// 主体营业点表
/**
 * 可充值?
 * 可消费? - 入账科目?
 */
import { DataTypes, UUIDV4 } from 'sequelize';
import { MySqlModel, getSequelize } from '../db';

class Outlets extends MySqlModel {

}

Outlets.init({
  id: {
    type: DataTypes.UUID, unique: 'id', allowNull: false, defaultValue: UUIDV4, validate: { isUUID: 4 }, primaryKey: true, comment: '主键'
  },
  hotel_id: {
    type: DataTypes.UUID, allowNull: false, validate: { isUUID: 4 }, comment: '主体'
  },
  code: {
    type: DataTypes.STRING(50), allowNull: false, comment: '代码'
  },
  name: {
    type: DataTypes.STRING(200), allowNull: false, comment: '名称'
  },
  phone: {
    type: DataTypes.STRING(50), allowNull: true, defaultValue: null, comment: '电话'
  },
  is_payment: {
    type: DataTypes.BOOLEAN, defaultValue: false, comment: '是否可以充值'
  },
  is_posting: {
    type: DataTypes.BOOLEAN, defaultValue: false, comment: '是否可以入账消费'
  },
  disabled: {
    type: DataTypes.BOOLEAN, defaultValue: false, comment: '是否禁用'
  },
  sequence: {
    type: DataTypes.INTEGER, allowNull: false, defaultValue: 1, comment: '序号'
  },
  reference: {
    type: DataTypes.STRING(500), allowNull: true, defaultValue: null, comment: '备注'
  },
  created_id: {
    type: DataTypes.UUID, allowNull: false, validate: { isUUID: 4 }, comment: '创建用户', editable: false
  },
  updated_id: {
    type: DataTypes.UUID, allowNull: false, validate: { isUUID: 4 }, comment: '更新用户', logger: true, editable: false, model: 'Users', column: 'login_name'
  },
  created_at: {
    type: DataTypes.DATE, allowNull: false, editable: false, comment: '创建时间'
  },
  updated_at: {
    type: DataTypes.DATE, allowNull: false, editable: false, comment: '更新时间'
  },
  version: {
    type: DataTypes.INTEGER, allowNull: false, defaultValue: 0, editable: false, comment: '版本控制'
  }
}, {
  sequelize: getSequelize(),
  tableName: 'outlets',
  comment: '营业点'
});

Outlets.associate = (db) => {
  Outlets.belongsTo(db.Hotels, {
    foreignKey: 'hotel_id',
    as: 'hotel',
    constraints: false
  });

  Outlets.hasOne(db.UserOutlets, {
    foreignKey: 'outlet_id',
    as: 'user_outlet',
    constraints: false
  });
};

Outlets.beforeDestroy(async (instance, options) => {
  const { transaction } = options;
  const ft = await getSequelize().models.TransactionDetails
    .findOne({
      where: {
        outlet_id: instance.id
      },
      transaction
    });
  if (ft) {
    throw new Error('In Used');
  }
});

export default Outlets;
